import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  HttpStatus,
  HttpCode,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { TodoReplyService } from './todo-reply.service';
import { CreateTodoReplyDto } from './dto/create-todo-reply.dto';
import { OssUtilService } from '../common/upload/oss-util.service';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';
import { v4 as uuidv4 } from 'uuid';

@Controller('todo-reply')
export class TodoReplyController {
  constructor(
    private readonly todoReplyService: TodoReplyService,
    private readonly ossUtilService: OssUtilService,
    private readonly uploadPicturesService: UploadPicturesService,
  ) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  create(@Body() createTodoReplyDto: CreateTodoReplyDto) {
    return this.todoReplyService.create(createTodoReplyDto);
  }

  // 上传待办回复图片接口
  @Post('uploadimg')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(@UploadedFile() file: any) {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const fileName = file.originalname;
    const suffixName = fileName.substring(fileName.lastIndexOf('.'));
    const newFileName = uuidv4() + suffixName;

    try {
      const result = await this.ossUtilService.uploadFile(
        'hasmarket',
        'todoreply',
        newFileName,
        file.buffer,
      );

      return {
        success: true,
        data: {
          url: result.url,
          name: result.name,
          originalName: fileName,
          size: file.size,
          mimeType: file.mimetype,
        },
        message: '上传成功',
      };
    } catch (error) {
      console.error('OSS上传错误:', error);
      throw new BadRequestException(`上传失败: ${error.message}`);
    }
  }

  // 添加图片记录到数据库
  @Post('addimageitem')
  async addImageItem(@Body() imageData: any) {
    try {
      const result = await this.uploadPicturesService.create({
        serviceId: imageData.serviceId,
        name: imageData.name,
        imageUrl: imageData.imageUrl,
        suffix: imageData.suffix || '.jpg',
      });

      return {
        success: true,
        data: result,
        message: '图片记录添加成功',
      };
    } catch (error) {
      throw new BadRequestException('图片记录添加失败: ' + error.message);
    }
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.todoReplyService.findById(+id);
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  remove(@Param('id') id: string) {
    return this.todoReplyService.remove(+id);
  }
} 